package org.openclinic.service.impl;

import java.util.Date;
import java.util.List;
import java.util.UUID;

import org.openclinic.domain.Attendant;
import org.openclinic.domain.User;
import org.openclinic.exception.DomainException;
import org.openclinic.exception.ErrorCodes;
import org.openclinic.repository.AttendantRepository;
import org.openclinic.service.AttendantService;
import org.openclinic.web.context.AttributeRetriever;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataIntegrityViolationException;
import org.springframework.stereotype.Service;

@Service
public class AttendantServiceImpl implements AttendantService {
	
	@Autowired
	private AttendantRepository attendantRepository;
	
	@Override
	public void delete(long id) {
		try {
			attendantRepository.delete(id);
		} catch (DataIntegrityViolationException e) {
			throw new DomainException("attendant", "name", ErrorCodes.FOREIGN_KEY_VIOLATED, String.valueOf(id));
		}
	}
	
	@Override
	public Attendant find(long id) {
		return attendantRepository.findOne(id);
	}
	
	@Override
	public Attendant find(String cpf, String password) {
		return attendantRepository.findByCpfAndPassword(cpf, password);
	}
	
	@Override
	public List<Attendant> list() {
		return attendantRepository.findAllAttendants();
	}
	
	@Override
	public Attendant save(Attendant attendant) {
		Date currentDate = new Date();
		
		if (attendant.getUserId() == null) {
			String password = UUID.randomUUID().toString().toUpperCase().substring(28).replace('A', 'S').replace('E', 'J');
			
			attendant.setActive(true);
			attendant.setPassword(password);
			attendant.setCreationDate(currentDate);
		}
		
		attendant.setLastUpdate(currentDate);
		return attendantRepository.save(attendant);
	}
	
	@Override
	public int updatePassword(String newPassword, String currentPassword) {
		User user = AttributeRetriever.getUserFromSession();
		return attendantRepository.updatePassword(newPassword, currentPassword, user.getUserId());
	}
}
